package com.robot.mvvm.vm.main

import android.app.Application
import androidx.databinding.BaseObservable
import androidx.databinding.ObservableField
import api.UserServiceFactory
import com.robot.base.base.vm.GLBaseViewModel
import com.robot.base.common.api.AbstractViewModelSubscriber
import com.robot.base.configs.AppConstants
import com.robot.base.configs.PrefsManager
import com.robot.base.util.LiveDataBus
import com.robot.base.util.arouter.ARouterUtil
import com.robot.mvvm.vm.login.LoginViewModel
import me.goldze.mvvmhabit.binding.command.BindingAction
import me.goldze.mvvmhabit.binding.command.BindingCommand
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent
import me.goldze.mvvmhabit.http.BaseResponse

class MyFragmentViewModel(application: Application) : GLBaseViewModel(application) {

    val imgUrl = ObservableField<String>()
    val name = ObservableField<String>()

    init {
        val userInfo = PrefsManager.getUserInfo()
        imgUrl.set(userInfo.avatar)
        name.set(userInfo.trueName)
    }

    val uc = UiChangeEvent()

    class UiChangeEvent {
        val logoutEvent = SingleLiveEvent<Void>()
    }

    val toPersonalCommand = BindingCommand<Any>(BindingAction {
        ARouterUtil.goToActivity(AppConstants.Router.Main.A_PERSONAL_INFO)
    })

    val toSignCommand = BindingCommand<Any>(BindingAction {

    })

    val toSettingCommand = BindingCommand<Any>(BindingAction {

    })
    val toDeviceCommand = BindingCommand<Any>(BindingAction {
        LiveDataBus.get().with(AppConstants.LiveKey.TO_MAIN_TAB, Int::class.java).postValue(1)
    })
    val clickLogoutCommand = BindingCommand<Any>(BindingAction {
        uc.logoutEvent.call()
    })


    fun logout() {
        showLoadingDialog()
        UserServiceFactory.logout()
            .subscribe(object : AbstractViewModelSubscriber<BaseResponse<String>>(this) {
                override fun onNext(t: BaseResponse<String>) {
                    dismissLoadingDialog()
                    PrefsManager.logout()
                }
            })
    }
}